package org.gcu.filestorage.controller;

import lombok.extern.slf4j.Slf4j;
import org.gcu.filestorage.api.ErrorCode;
import org.gcu.filestorage.pojo.*;
import org.gcu.filestorage.serive.AccountInfoService;
import org.gcu.filestorage.serive.ApplyInfoService;
import org.gcu.filestorage.serive.MailService;
import org.gcu.filestorage.uitls.TokenUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@Slf4j
@RestController
public class ApprovalController {

    private final AccountInfoService accountInfoService;
    private final MailService mailService;
    private final ApplyInfoService applyInfoService;

    private final FileController fileController;

    @Autowired
    public ApprovalController(AccountInfoService accountInfoService,
                              MailService mailService,
                              ApplyInfoService applyInfoService,
                              FileController fileController) {
        this.accountInfoService = accountInfoService;
        this.mailService = mailService;
        this.applyInfoService = applyInfoService;
        this.fileController = fileController;
    }


    @PostMapping("/approveRegister")
    public RequestResult<Boolean> approveRegister(@RequestBody ApprovalRegisterInfo approvalRegisterInfo) {
        log.info("approveRegister(), approvalInfo=" + approvalRegisterInfo);
        RequestResult<Boolean> requestResult = new RequestResult<>();
        mailService.sendSimpleMail(approvalRegisterInfo.getEmailInfo().getReceiver(),
                approvalRegisterInfo.getEmailInfo().getSubject(),
                approvalRegisterInfo.getEmailInfo().getContent());
        boolean b = this.accountInfoService.updateRegisterStatus(approvalRegisterInfo.getAccount(), approvalRegisterInfo.getRegisterStatus());
        requestResult.setData(b);
        requestResult.setMessage(b ? "审批注册状态成功" : "审批注册状态失败");
        requestResult.setResCode(b ? ErrorCode.SUCCESS : ErrorCode.APPROVAL_REGISTER_FAILURE);
        return requestResult;
    }

    @PostMapping("/rejectRegister")
    public RequestResult<Boolean> rejectRegister(@RequestBody ApprovalRegisterInfo approvalRegisterInfo) {
        log.info("rejectRegister(), approvalInfo=" + approvalRegisterInfo);
        RequestResult<Boolean> requestResult = new RequestResult<>();
        mailService.sendSimpleMail(approvalRegisterInfo.getEmailInfo().getReceiver(),
                approvalRegisterInfo.getEmailInfo().getSubject(),
                approvalRegisterInfo.getEmailInfo().getContent());
        // 将拒绝注册的用户从数据库中删除
        boolean b = this.accountInfoService.deleteAccountInfo(approvalRegisterInfo.getAccount());
        requestResult.setData(b);
        requestResult.setMessage(b ? "拒绝注册状态成功" : "拒绝注册状态失败");
        requestResult.setResCode(b ? ErrorCode.SUCCESS : ErrorCode.REJECT_REGISTER_FAILURE);
        return requestResult;
    }


    @PostMapping("/approveApply")
    public RequestResult<Boolean> approveApply(@RequestHeader("Authorization") String token, @RequestBody Map<String, String> requestParams) {
        log.info("approveApply(), requestParams=" + requestParams);
        RequestResult<Boolean> requestResult = new RequestResult<>();
        String account = TokenUtil.parseAccount(token);
        int applyStatus = Integer.parseInt(requestParams.getOrDefault("applyStatus", "1"));
        long applyVolume = Long.parseLong(requestParams.getOrDefault("applyVolume", "0"));
        String approvalDesc = requestParams.getOrDefault("approvalDesc", "");
        int id = Integer.parseInt(requestParams.getOrDefault("id", "0"));
        int applyType = Integer.parseInt(requestParams.getOrDefault("applyType", "1"));
        boolean recordResult = this.applyInfoService.updateApplyRecord(id, applyStatus, approvalDesc);
        boolean statusResult;
        if (applyType == 1) { // 新建容量
            statusResult = this.applyInfoService.insertNewSpaceStatus(account, applyVolume, 0, applyVolume);
            boolean createResult = fileController.createBucket(account);
            requestResult.setData(recordResult && statusResult && createResult);
            requestResult.setMessage(recordResult && statusResult && createResult? "审批申请状态成功" : "审批申请状态失败");
            requestResult.setResCode(recordResult && statusResult && createResult ? ErrorCode.SUCCESS : ErrorCode.APPROVAL_APPLY_FAILURE);
        } else { // 修改容量
            statusResult = this.applyInfoService.updateSpaceStatus(account, applyVolume, 0, applyVolume);
            requestResult.setData(recordResult && statusResult);
            requestResult.setMessage(recordResult && statusResult? "审批申请状态成功" : "审批申请状态失败");
            requestResult.setResCode(recordResult && statusResult ? ErrorCode.SUCCESS : ErrorCode.APPROVAL_APPLY_FAILURE);
        }
        return requestResult;
    }


    @PostMapping("/rejectApply")
    public RequestResult<Boolean> rejectApply(@RequestBody Map<String, String> requestParams) {
        log.info("rejectApply(), requestParams=" + requestParams);
        RequestResult<Boolean> requestResult = new RequestResult<>();
        int applyStatus = Integer.parseInt(requestParams.getOrDefault("applyStatus", "1"));
        int id = Integer.parseInt(requestParams.getOrDefault("id", "0"));
        String approvalDesc = requestParams.getOrDefault("approvalDesc", "");
        boolean updateResult = this.applyInfoService.updateApplyRecord(id, applyStatus,approvalDesc);
        requestResult.setData(updateResult);
        requestResult.setMessage(updateResult ? "拒绝申请状态成功" : "拒绝申请状态失败");
        requestResult.setResCode(updateResult ? ErrorCode.SUCCESS : ErrorCode.REJECT_APPLY_FAILURE);
        return requestResult;
    }

    @PostMapping("/queryApplyRecordByStatus")
    public RequestResult<String> queryApplyRecordByStatus(@RequestParam int applyStatus) throws JSONException {
        log.info("queryApplyRecordByStatus(), applyStatus="+applyStatus);
        RequestResult<String> requestResult = new RequestResult<>();
        List<ApplyRecord> applyRecordList = applyInfoService.queryApplyRecordByStatus(applyStatus);
        JSONArray jsonArray = new JSONArray();
        for (ApplyRecord applyRecord : applyRecordList) {
            JSONObject jsonObject = new JSONObject();
            AccountInfo accountInfo = accountInfoService.queryAccountInfo(applyRecord.getAccount());
            jsonObject.put("id", applyRecord.getId());
            jsonObject.put("account", applyRecord.getAccount());
            jsonObject.put("applyVolume", applyRecord.getApplyVolume());
            jsonObject.put("applyTime", applyRecord.getApplyTime());
            jsonObject.put("realName", accountInfo.getRealName());
            jsonObject.put("department", accountInfo.getDepartment());
            jsonObject.put("applyType", applyRecord.getApplyType());
            jsonObject.put("applyReason", applyRecord.getApplyReason());
            jsonArray.put(jsonObject);
        }
        requestResult.setResCode(ErrorCode.SUCCESS);
        requestResult.setMessage("查询成功");
        requestResult.setData(jsonArray.toString());
        return requestResult;
    }
}
